package cn.patient.pp.framework.excel.core.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;

public class NullableNumberConverter implements Converter<Number> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Number.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    // 将表格数据转换成对应类型数字(空值返回null)
    @Override
    public Number convertToJavaData(ReadCellData<?> cellData,
                                    ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        if (cellData == null || cellData.getNumberValue() == null) {
            return null;
        }

        BigDecimal number = cellData.getNumberValue();
        Class<?> targetType = contentProperty.getField().getType();

        if (targetType == Integer.class) {
            return number.intValue();
        } else if (targetType == Long.class) {
            return number.longValue();
        } else if (targetType == Double.class) {
            return number.doubleValue();
        } else if (targetType == Float.class) {
            return number.floatValue();
        } else if (targetType == BigDecimal.class) {
            return number;
        }

        // 默认返回 BigDecimal
        return number;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Number value,
                                               ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData<>((String) null);
        }
        return new WriteCellData<>(new BigDecimal(value.toString()));
    }
}
